package com.ep.thirdPlatformProject.maycur.helper;


import com.ep.thirdPlatformProject.maycur.entity.login.MayCurLoginParam;
import com.ep.thirdPlatformProject.maycur.entity.login.MayCurToken;
import com.ep.thirdPlatformProject.maycur.enums.MayCurApiEnum;
import com.ep.thirdPlatformProject.system.config.maycur.MayCurProperties;
import com.ep.thirdPlatformProject.system.util.OkHttpUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.time.Clock;
import java.time.Instant;


@Slf4j
@Component
@RequiredArgsConstructor
public class MayCurLoginHelper {

    private final MayCurCommonHelper commonHelper;


    private final MayCurProperties mayCurProperties;
    /**
     * 登录方法，用于获取当前系统的登录令牌（Token）。
     * 该方法首先构造登录请求参数，然后向指定的API发送登录请求，最后解析响应获取Token。
     *
     * @return MayCurToken 登录成功后返回的Token对象。
     * @throws RuntimeException 如果获取Token失败，则抛出运行时异常。
     */
    public MayCurToken login() {
        try {
            // 获取当前时间戳，并基于时间戳、appCode和appSecretOrigin生成加密字符串
            long timestamp = getCurrentTimestamp();

            //生成应用密钥
            String appSecret = commonHelper.generateAppSecret(timestamp);

            // 构建登录请求参数
            MayCurLoginParam loginParam = buildLoginParam(timestamp, appSecret);
            log.info("loginParam:{}", loginParam);

            // 使用OkHttp发送登录请求，并获取响应
            String response = sendLoginRequest(loginParam);

            // 检查响应是否表示登录成功
            if (commonHelper.isReturnSuccessful(response)) {
                log.error("获取token失败! 结果为：{}", response);
                throw new TokenAcquisitionException("获取token失败!");
            }
            log.info("登录接口获取到的response:{}", response);

            // 解析响应，返回Token对象
            return commonHelper.parseResponseToObject(response, MayCurToken.class);

        } catch (Exception ex) {
            log.error("登录过程中出现异常：", ex);
            throw new TokenAcquisitionException("登录过程中出现异常", ex);
        }
    }


    private MayCurLoginParam buildLoginParam(long timestamp, String appSecret) {
        // 实现构建登录请求参数的逻辑
        return new MayCurLoginParam()
                .appCode(mayCurProperties.getAppCode())
                .timestamp(String.valueOf(timestamp))
                .secret(appSecret);
    }

    private String sendLoginRequest(MayCurLoginParam loginParam) {
        // 使用OkHttp发送登录请求，并获取响应的逻辑
        return OkHttpUtils.builder()
                .url(commonHelper.constructUrl(MayCurApiEnum.GET_TOKEN.getUrl()))
                .addJsonParam(loginParam)
                .post(true)
                .sync();
    }

    /**
     * 获取当前时间戳
     *
     * @return {@link Long}
     */
    private Long getCurrentTimestamp() {
        return Instant.now(Clock.systemDefaultZone()).toEpochMilli();
    }


    static class TokenAcquisitionException extends RuntimeException {
        public TokenAcquisitionException(String message) {
            super(message);
        }

        public TokenAcquisitionException(String message, Throwable cause) {
            super(message, cause);
        }
    }
}
